package com.hengpeng.itfin.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.util.DES;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.service.EmailService;
import com.hengpeng.itfin.tools.TemplateUtil;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.userInfo.SendEmailRequest;
import com.hengpeng.itfinbase.persist.EmailLog;
import com.hengpeng.itfinbase.persist.EmailLog.EmailState;
import com.hengpeng.itfinbase.persist.EmailLog.EmailType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoStatus;
import com.hengpeng.itfinbase.persist.VerifyCode;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;

/**
 * <pre>
 * 邮件服务类
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-7-31
 */
@Transactional
@Service
@Lazy
public class EmailServiceImpl extends BaseServiceImpl implements EmailService
{

	@Override
	public List<EmailLog> findEmailForNotSend(int count)
	{
		List<EmailLog> list = serviceFactory.getPersistService().listByNamedQuery(EmailLog.class, "email.queryNotSend",
				count, 1, new Object[] { EmailState.NOTSEND });
		List<EmailLog> newList = new ArrayList<EmailLog>();
		for (EmailLog email : list)
		{
			email.setState(EmailState.SENDING);
			newList.add(serviceFactory.getPersistService().update(email));
		}
		return newList;
	}

	@Override
	public ServiceResult<Boolean> findPassAffirmByEmail(String username, String verifyCode, VerifyType type)
	{
		return null;
	}

	@Override
	public ServiceResult<Boolean> sendSubscribeActive(String url, String storeId, String betCardNo, String username,
			String email, VerifyType type)
	{
		return null;
	}

	@Override
	public ServiceResult<Boolean> subScribeAffirmByEmail(String username, String verifyCode, VerifyType type)
	{
		return null;
	}

	@Override
	public int resetAllEmailForSending()
	{
		return serviceFactory.getDaoFactory().getEmailLogDao().resetAllEmailForSending();
	}

	@Override
	public boolean sendEmail(EmailType type, int sendLevel, String storeId, String toEmail, String title, String content)
	{
		return false;
	}

	@Override
	public ServiceResult<Boolean> sendfindPassActive(String url, String storeId, String betCardNo, String username,
			String email, VerifyType type)
	{
		return null;
	}

	@Override
	public boolean sendRegisterActive(String url, String storeId, String betCardNo, String username, String email)
	{
		return false;
	}
	
//	@Override
//	public ResponseMessage sendActiveEmail(String url, String username,
//			String email, String activeCode, String returnUrl, VerifyType type) {
//		ResponseMessage response=new ResponseMessage();
//		UserInfo user=serviceFactory.getUserInfoService().getUserByUserName(username);
//		if(StringUtils.isEmpty(email) || type==null || returnUrl==null){
//			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.CommonCode.DATA_NOT_VALIDATA,
//			"参数错误");
//		}
//		if(user==null){
//			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND,
//			"用户不存在");
//		}
//		
//		try
//		{
//			// 邮箱唯一性校验
//			if (!email.equals(user.getEmail()))
//			{
//				DynamicQuery query = new DynamicQuery(UserInfo.class);
//				query.addProjection(Projections.count());
//				query.eq("email",email);
//				int count = serviceFactory.getPersistService().countByDynamicQuery(query);
//				if (count > 0)
//				{
//					return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.EMAIL_HAD_EXIST,
//					"邮箱已经存在");
//				}
//			}else{
//				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.EMAIL_HAD_EXIST,
//				"邮箱已经存在");
//			}
//			
//			//网站名
//			String webName=SystemConfigUtil.getConfigValue("webName");
//			//网站域名
//			String domainName=SystemConfigUtil.getConfigValue("domainName");
//			
//			EmailLog emailLog = new EmailLog();
//			emailLog.setType(EmailType.VALIDEMAIL);
//			emailLog.setUsername(username);
//			emailLog.setEmail(email);
//			emailLog.setTitle("用户邮箱验证");
//
//			// 生成找回密码激活URL
//			Calendar paseDate = Calendar.getInstance();
//			paseDate.add(Calendar.DAY_OF_MONTH, 1);
//			DES des = new DES();
//			VerifyCode verifyCode = serviceFactory.getDaoFactory().getVerifyCodeDao()
//					.create(username, type, paseDate.getTime());
//			String activeUrl = url + "?username=" + des.encrypt(username) + "&verifyCode=" + verifyCode.getValue()
//					+ "&email=" + des.encrypt(email) + "&returnUrl="
//					+ des.encrypt(returnUrl);
//			emailLog.setContent(TemplateUtil.makeTemplateContent(username,activeUrl,
//					webName,domainName, "",activeCode, "validEmail.ftl"));
//			emailLog.setState(EmailState.NOTSEND);
//			emailLog.setSendTime(new Date());
//			emailLog.setRetryCount(0);
//			emailLog.setSendLevel(10);//设置级别(值越大越优先)
//			// 记录到邮件列表
//			serviceFactory.getPersistService().save(emailLog);
//			return response;
//		}
//		catch (Exception e)
//		{
//			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.CommonCode.TRANS_FAIL,
//			"发送失败");
//		}
//	}

	/**
	 * 验证邮箱
	 * @param url
	 * @param username
	 * @param email
	 * @param returnUrl
	 * @param type
	 * @return
	 */
	@Override
	public ResponseMessage sendValidEmail(String url,String username,
			String email,String activeCode, String successUrl,String errorUrl, VerifyType type)
	{
		ResponseMessage response=new ResponseMessage();
		UserInfo user=serviceFactory.getUserInfoService().getUserByUserName(username);
		if(StringUtils.isEmpty(email) || type==null || StringHelper.isEmpty(successUrl) || StringHelper.isEmpty(errorUrl)){
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.CommonCode.DATA_NOT_VALIDATA,
			"参数错误");
		}
		if(user==null){
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND,
			"用户不存在");
		}
		
		try
		{
			// 邮箱唯一性校验
//			if (!email.equals(user.getEmail()))
//			{
//				DynamicQuery query = new DynamicQuery(UserInfo.class);
//				query.addProjection(Projections.count());
//				query.eq("email",email);
//				int count = serviceFactory.getPersistService().countByDynamicQuery(query);
//				if (count > 0)
//				{
//					return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.EMAIL_HAD_EXIST,
//					"邮箱已经存在");
//				}
//			}else{
//				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.EMAIL_HAD_EXIST,
//				"邮箱已经存在");
//			}
			
			//网站名
			String webName=SystemConfigUtil.getConfigValue("webName");
			//网站域名
			String domainName=SystemConfigUtil.getConfigValue("domainName");
			
			EmailLog emailLog = new EmailLog();
			emailLog.setType(EmailType.VALIDEMAIL);
			emailLog.setUsername(username);
			emailLog.setEmail(email);
			emailLog.setTitle("用户邮箱验证");

			// 生成找回密码激活URL
			Calendar paseDate = Calendar.getInstance();
			paseDate.add(Calendar.DAY_OF_MONTH, 1);
			DES des = new DES();
			VerifyCode verifyCode = serviceFactory.getDaoFactory().getVerifyCodeDao()
					.create(username, type, paseDate.getTime());
			String activeUrl = url + "?username=" + des.encrypt(username) + "&verifyCode=" + verifyCode.getValue()
					+ "&email=" + des.encrypt(email) + "&successUrl="+ des.encrypt(successUrl) + "&errorUrl="+des.encrypt(errorUrl);
			emailLog.setContent(TemplateUtil.makeTemplateContent(username,activeUrl,
					webName,domainName, "", activeCode,"validEmail.ftl"));
			emailLog.setState(EmailState.NOTSEND);
			emailLog.setSendTime(new Date());
			emailLog.setRetryCount(0);
			emailLog.setSendLevel(10);//设置级别(值越大越优先)
			// 记录到邮件列表
			serviceFactory.getPersistService().save(emailLog);
			return response;
		}
		catch (Exception e)
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.CommonCode.TRANS_FAIL,
			"发送失败");
		}
	}

	@Override
	public ResponseMessage confirmEmailForValid(SendEmailRequest request)
	{
		ResponseMessage response=new ResponseMessage();
		// 邮箱验证邮件确认
		UserInfo user=serviceFactory.getUserInfoService().getUserByUserName(request.getUsername());
		if (user == null)
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.ACCOUNT_NOT_FOUND,
			"用户不存在");
		}
		// 检查用户状态是否正常
		if (user.getStatus() != UserInfoStatus.NORMAL)
		{
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.MEMBER_STATUS_EXCEPTION,
			"用户状态不正确");
		}
		VerifyCode bean = serviceFactory.getPersistService().getByNamedQuery(VerifyCode.class,
				"verifyCode.getByUserNameAndValueAndType",
				new Object[] {user.getUserName(), request.getVerifyCode(), request.getType() });
		if (bean == null)
		{
			// 非法链接
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.RESET_PASS_URL_ERROR,
			"链接错误");
		}
		if (bean.getValid().equals(BoolValue.YES))
		{
			if (bean.getPastDate().before(new Date()))
			{// 过期
				bean.setValid(BoolValue.NO);
				serviceFactory.getPersistService().update(bean);
				return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.RESET_PASS_URL_INVALIDATION,
				"已经过期");
			}
			else
			{// 有效
				String email = request.getEmail();
				// 邮箱唯一性校验
				if (email != null && !email.equals(user.getEmail()))
				{
					DynamicQuery query = new DynamicQuery(UserInfo.class);
					query.addProjection(Projections.count());
					query.eq("email", email);
					int count = serviceFactory.getPersistService().countByDynamicQuery(query);
					if (count > 0)
					{
						return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.EMAIL_HAD_EXIST,
						"邮箱已经存在");
					}
				}
				// 修改用户邮箱为当前验证邮箱和邮箱是否验证标识
				user.setEmail(email);
				user.setIsEmailCheck(BoolValue.YES);
				serviceFactory.getPersistService().update(user);
				// 验证成功，使验证码失效
				bean.setValid(BoolValue.NO);
				serviceFactory.getPersistService().update(bean);
				return response;
			}
		}
		else
		{// 效检码失效
			return MessageUtil.getErrorResponseMessage(ResponseMessage.class,RespCodeConstants.MemberCode.MEMBER_FIND_PASS_AFFIRM_CODE_INVALID,
					"效检码失效");
		}
	}

	@Override
	public ResponseMessage cancelSubscribe(String betCardNo)
	{
		return null;
	}
	}
